package com.d3works.apps.account.web;

import com.d3works.apps.account.db.Reconcile;
import com.d3works.apps.account.db.repo.ReconcileRepository;
import com.d3works.apps.account.service.ReconcileService;
import com.d3works.exception.ResponseMessageType;
import com.d3works.exception.service.TraceBackService;
import com.d3works.inject.Beans;
import com.d3works.rpc.ActionRequest;
import com.d3works.rpc.ActionResponse;
import com.google.inject.Singleton;
import java.util.Objects;
import java.util.stream.Collectors;

@Singleton
public class ReconcileController {

  // Unreconcile button
  public void unreconcile(ActionRequest request, ActionResponse response) {

    Reconcile reconcile = request.getContext().asType(Reconcile.class);

    try {
      Beans.get(ReconcileService.class)
          .unreconcile(Beans.get(ReconcileRepository.class).find(reconcile.getId()));
      response.setReload(true);
    } catch (Exception e) {
      TraceBackService.trace(response, e);
    }
  }

  // Reconcile button
  public void reconcile(ActionRequest request, ActionResponse response) {

    Reconcile reconcile = request.getContext().asType(Reconcile.class);

    try {
      Beans.get(ReconcileService.class)
          .confirmReconcile(
              Beans.get(ReconcileRepository.class).find(reconcile.getId()), true, true);
      response.setReload(true);
    } catch (Exception e) {
      TraceBackService.trace(response, e);
    }
  }

  public void checkReconcile(ActionRequest request, ActionResponse response) {
    Reconcile reconcile = request.getContext().asType(Reconcile.class);

    try {
      Beans.get(ReconcileService.class)
          .checkReconcile(Beans.get(ReconcileRepository.class).find(reconcile.getId()));
    } catch (Exception e) {
      TraceBackService.trace(response, e, ResponseMessageType.ERROR);
    }
  }

  public void setMoveLineDomain(ActionRequest request, ActionResponse response, boolean isDebit) {
    try {
      Reconcile reconcile = request.getContext().asType(Reconcile.class);

      String moveLineIds =
          Beans.get(ReconcileService.class).getAllowedMoveLines(reconcile, isDebit).stream()
              .map(Objects::toString)
              .collect(Collectors.joining(","));

      String moveLinePrefix = isDebit ? "debit" : "credit";
      response.setAttr(
          String.format("%sMoveLine", moveLinePrefix),
          "domain",
          String.format("self.id IN (%s)", moveLineIds.isEmpty() ? "0" : moveLineIds));
    } catch (Exception e) {
      TraceBackService.trace(response, e);
    }
  }

  public void setDebitMoveLineDomain(ActionRequest request, ActionResponse response) {
    this.setMoveLineDomain(request, response, true);
  }

  public void setCreditMoveLineDomain(ActionRequest request, ActionResponse response) {
    this.setMoveLineDomain(request, response, false);
  }
}
